package com.mqb.n8;

import java.time.DayOfWeek;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * @author mqb
 * @date 2021/5/2 22:00
 */
public class TestSchedule {
    // 如何让每周四 18:00:00 定时执行任务
    public static void main(String[] args) {
        ScheduledExecutorService pool = Executors.newScheduledThreadPool(1);

        // initialDelay 表示当前时间和周四的时间差
        LocalDateTime now = LocalDateTime.now();    // 获取当前时间
        LocalDateTime with = now.withHour(18).withMinute(0).withSecond(0).with(DayOfWeek.THURSDAY); // 修改为周四时间

        // 如果当前时间大于本周周四，则要找到下周周四
        if (now.compareTo(with) > 0) {
            with = with.plusWeeks(1);
        }

        // 获取现在时间到下个周四的时差
        long initialDelay = Duration.between(now, with).toMillis();

        // period 一周的间隔时间
        long period = 1000 * 60 * 60 * 24 * 7;

        pool.scheduleAtFixedRate(() -> {
            System.out.println("running");
        }, initialDelay, period, TimeUnit.MILLISECONDS);
    }
}
